<template>
  <div class="pay-vip por">
    <header class="header" v-if="!isChannel || productInfo.channel_id === 23 || hasType.includes(openType)">
      <img :src="product.icon" class="ico fl vam">
      <div class="name">{{product.name}}</div>
      <div class="desc wot1">{{product.desc}}</div>
    </header>
    <div class="set-meal">
      <ul class="list">
        <li @click="checkItem(k)" class="item bsb por"
            :class="{active: k === curr}" v-for="(item, k) in list"
            :key="k">
          <div class="price fr tar">
            <div class="now">¥<span class="num">{{item.price / 100}}</span></div>
            <div class="old">¥{{item.price * 2 / 100 }}</div>
          </div>
          <div class="text jcb flex-col">
            <div class="name">{{item.price_name}}</div>
            <scroll-text :text="item.cost_price"></scroll-text>
          </div>
          <div class="checked poa t0 r0 vam tac dn">
            <van-icon name="success"/>
          </div>
        </li>
      </ul>
    </div>

    <div class="discount" v-show="!isWx || productInfo.channel_id !== 23">
      <van-cell v-if="!hasType.includes(openType)" title="优惠券" is-link :value="currDiscount.name || '选择优惠券'"
                @click="showDiscount = true"/>
      <van-cell title="小计" :value="'¥' + price"/>
      <van-cell title="优惠券" :value="currDiscount.price || '0.00'"/>
    </div>

    <van-popup class="discount-popup" v-model="showDiscount" position="bottom">
      <div class="popup-title">优惠券</div>
      <van-tabs v-model="activeDiscount" color="#ff8611" :ellipsis="false">
        <van-tab :title="`可使用优惠券(${usable.length})`"></van-tab>
        <van-tab :title="`不可使用优惠券(${disable.length})`"></van-tab>
      </van-tabs>
      <div class="card-list ova bsb">
        <discount-card :cannot="!!activeDiscount" :item="item"
                       :active="item.id === discount.id"
                       v-for="(item, i) in (activeDiscount ? disable : usable)" :key="i"
                       @check="discount = discount.id === item.id ? {} : item "></discount-card>
      </div>
      <div class="use-discount abs-c tac" @click="currDiscount = discount; showDiscount = false">确定</div>
    </van-popup>

    <div class="notice">
      <div class="title">购买须知</div>
      <div class="inner wspl" v-if="hasType.includes(openType)">1. 小度音箱仅支持带屏音频购买，无屏音箱购买后无法在音箱上使用；
        2. 购买会员后，可观看应用内所有课程视频；
        3. 购买会员后，小度音箱、手机端、平板端和电视端都可观看，
        &nbsp;&nbsp;&nbsp;&nbsp;<a :href="product.link || product.apkLink"
                                   style="color: #3071f4">点击下载APP</a>；
        4. VIP会员属于虚拟物品，支付成功后会员即时生效,不支持退换噢。
      </div>
      <div class="inner wspl" v-else>1. 购买会员后，可观看应用内所有课程视频；
        <template v-if="!isChannel || productInfo.channel_id === 23">2. 购买会员后，手机端、平板端和电视端都可观看，
          &nbsp;&nbsp;&nbsp;&nbsp;<a :href="product.link || product.apkLink"
                                     style="color: #3071f4">点击下载APP</a>；
          3. VIP会员属于虚拟物品，支付成功后会员即时生效,不支持退换噢。
        </template>
        <template v-else>2. VIP会员属于虚拟物品，支付成功后会员即时生效,不支持退换噢。
        </template>
      </div>
    </div>
    <div class="pay-btn pof b0 vw100 bsb">
      <div class="btn h100 fr tac" @click="pay">确认支付</div>
      <div class="money">总计
        <span class="num">
          ¥ {{((price + (currDiscount.price * 1 || 0)) > .01 ? (price + (currDiscount.price * 1 || 0)) : .01).toFixed(2)}}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { isXxtb, isChannel } from '@/config/config';

  export default {
    name: 'PayVip',
    data() {
      return {
        isXxtb,
        isChannel,
        payLock: false,
        product: {},
        discount: {},
        currDiscount: {},
        showDiscount: false,
        activeDiscount: 0,
        list: [],
        disable: [],
        usable: [],
        uid: '',
        openType: '',
        hasType: ['qrcode', 'link'],
        curr: 0,
        price: 0
      };
    },
    computed: {
      ...mapGetters([
        'appList',
        'wxUserInfo',
        'productInfo',
        'isWx',
        'userInfo'
      ])
    },
    watch: {
      curr(val) {
        let item = this.list[val];
        this.price = item ? item.price / 100 : 0;
        this.currDiscount = Object.assign({}, this.currDiscount);
      },
      currDiscount(val) {
        if (!val.id) return;
        val.name = val.reward_discount * 1 || val.reward_price / 100;
        val.name += val.reward_discount * 1 ? '折优惠券' : '元抵用券';
        if (val.reward_discount * 1) {
          val.price = -this.price * (1 - val.reward_discount / 10);
        } else {
          val.price = -val.reward_price / 100;
        }
        val.price = val.price.toFixed(2);
      }
    },
    methods: {
      getProduct() {
        let lists = [];
        let openTypeId = this.$route.query.cid;
        let tid = this.$route.query.tid;
        this.openType = this.$route.query.open_type;
        this.appList.map(e => lists.push(...e.list));
        if (isChannel && this.productInfo.channel_id !== 23 && !this.hasType.includes(this.openType)) {
          this.product = lists.find(e => e.pid === (isXxtb ? 1 : 9));
          this.product.pid = this.productInfo.product_id;
        } else {
          this.product = lists.find(e => e.pid === +this.$route.params.id) || {};
        }
        if (this.hasType.includes(this.openType)) {
          this.product.terminal_id = this.openType === 'qrcode' ? tid || 3 : 5;
          if (openTypeId) {
            this.product.channel_id = +openTypeId;
          }
        }
        return this.product;
      },
      // 获取套餐列表
      getList() {
        let pid = this.product.pid;
        let params = {
          product_id: pid,
          channel_id: this.productInfo.channel_id,
          terminal_id: this.productInfo.terminal_id,
          uid: this.uid
        };
        if (this.hasType.includes(this.openType)) {
          params.channel_id = this.product.channel_id;
          params.terminal_id = this.product.terminal_id;
        }
        this.http.$post('api/price.product/get_vip_price_list', params).then(res => {
          if (isChannel && this.productInfo.channel_id !== 23 && !this.hasType.includes(this.openType)) {
            this.list = res.list;
          } else {
            this.list = res.list.filter(e => e.price_type === 3 || (pid > 2 && pid < 9 ? e.price_type === 2 : e.price_type === 5));
          }
          this.list.forEach(e => {
            e.price = e.real_pay || e.price;
          });
          this.list.length && (this.price = this.list[this.curr].price / 100);
        }).catch(this.$err);
      },

      // 选择套餐
      checkItem(k) {
        this.curr = this.curr === k ? '' : k;
      },

      // 优惠券列表
      getDiscount() {
        if (this.hasType.includes(this.openType)) {
          return;
        }
        this.http.$post('wxcat/api/coupon_list', {
          uid: this.uid,
          product_id: this.product.pid
        }).then(res => {
          this.usable = res.usable;
          this.disable = res.disable;
          this.currDiscount = res.usable[0] || {};
          this.discount = this.currDiscount;
        }).catch(this.$err);
      },

      // 确认支付
      pay() {
        if (this.payLock) {
          return;
        }
        this.payLock = true;
        if (this.curr === '') return this.$toast.error('请选择一个套餐');
        let item = this.list[this.curr];
        let params = {
          uid: this.uid, // #用户ID
          channel_id: this.productInfo.channel_id, // #渠道ID
          terminal_id: this.productInfo.terminal_id, // #终端ID,
          product_id: this.product.pid, // #产品ID
          type: 1, // #类型
          type_id: 1, //4 #支付类型ID 4 微信H5支付
          months: [-1, 1, 3, 12, 24, 36, 0, 120, 6][item.price_type], // #购买月数
          openid: this.wxUserInfo.openid,// #小程序下用户openid
          price_type: item.price_type, // #套餐类型
          coupon_id: this.currDiscount.id // #优惠券id
          // course_id: '' // #课程ID
        };
        let url = 'wxcat/weixin_pay/wechat_' + (isChannel && this.productInfo.channel_id !== 23 ? 'channel_jsapi_pay' : 'jsapi_pay_fenxiao');
        if (this.hasType.includes(this.openType)) {
          url = 'wxcat/weixin_pay/wechat_channel_jsapi_pay';
          params.channel_id = this.product.channel_id;
          params.terminal_id = this.product.terminal_id;
        }
        this.http.$post(url, params).then(res => {
          let parameters = res.parameters;
          parameters.timestamp = parameters.timeStamp;
          parameters.success = () => {
            this.checkOrder({ out_trade_no: res.out_trade_no });
          };
          // delete parameters.appId;
          delete parameters.timeStamp;
          // alert(JSON.stringify(parameters));
          wx.chooseWXPay(parameters);
        }).catch(this.$err).finally(() => {
          this.payLock = false;
        });
      },

      // 查询订单状态
      checkOrder(params) {
        params.product_id = 0;
        let url = 'wxcat/weixin_pay/queryorder_' + (isChannel && this.productInfo.channel_id !== 23 ? 'channel' : 'fenxiao');
        if (this.hasType.includes(this.openType)) {
          url = 'wxcat/weixin_pay/queryorder_channel';

        }
        this.http.$post(url, params).then(res => {
          this.util.getUserInfoApi();
          if (isChannel && this.productInfo.channel_id !== 23 && !this.hasType.includes(this.openType)) {
            this.$toast.success('支付成功');
            setTimeout(() => {
              this.$router.replace('/');
            }, 2000);
          } else {
            this.$router.replace({
              name: 'PaySuccess',
              query: {
                name: this.list[this.curr].name,
                pid: this.product.pid
              }
            });
          }
        }).catch(err => {
          if (err.code * 1 === 10005) {
            setTimeout(() => {
              this.checkOrder(params);
            }, 1000);
          } else {
            this.$err(err);
          }
        });
      }
    },
    async created() {
      if (!this.getProduct().pid) return this.$router.go(-1);
      if (this.util.reload()) return;
      this.userInfo.uid || await this.util.login('', this.$route.fullPath);
      try {
        await this.util.setWxConfig(['chooseWXPay']);
      } catch (e) {
        this.$err(e);
      }
      this.uid = this.userInfo.uid;
      // 统计进入
      let { pid: product_id, channel_id, terminal_id } = this.product;
      this.hasType.includes(this.openType) && this.http.$post('api/user/add_pay_click', {
        uid: this.userInfo.uid,
        product_id,
        channel_id,
        terminal_id,
        type: this.openType === 'link' ? 2 : 1
      }).then(console.log).catch(console.log);

      this.getList();
      this.getDiscount();
    }
  };
</script>

<style scoped lang="less">

  .pay-vip {
    background-color: #fff;

    .title {
      padding: 1.88rem 0 .88rem 1.28rem;
      line-height: 1;
      color: #444;
      font-size: .94rem;
      background: url(../../images/cashout/circle_icon.png) no-repeat .63rem 1.56rem;
      background-size: 1.47rem 1.47rem;
    }

    .header {
      background: url(../../images/pay/img_bg_h.png) no-repeat center center / 100%;
      padding: 1.41rem .75rem;
      height: 3.75rem;
      font-size: 1.31rem;
      line-height: 1.8;
      color: #fff;

      .ico {
        margin-right: .63rem;
        width: 3.75rem;
        height: 3.75rem;
      }

      .desc {
        line-height: 1rem;
        font-size: .88rem;
        opacity: .6;
      }
    }

    .set-meal {
      padding-top: 2.19rem;
      border-bottom: #f5f5f5 solid .63rem;

      .list {
        padding: 0 .75rem 1.25rem;
      }

      .item {
        padding: 1.16rem 1.5rem;
        /*height: 5rem;*/
        border-radius: 0.31rem;
        background-color: #ffffff;
        border: solid .06rem #cfcfcf;
        line-height: 1;

        &.active {
          background-color: lighten(#ff8611, 45%);
          border-color: #ff8611;

          .checked {
            display: block;

            .van-icon {
              line-height: 1.25rem;
            }
          }
        }

        & + .item {
          margin-top: .94rem;
        }

        .text {
          width: 60%;
          height: 2.75rem;
        }

        .name {
          white-space: nowrap;
          font-size: 1.25rem;
          font-weight: bold;
          color: #333;
        }

        .desc {
          font-size: .88rem;
          color: #666;
        }

        .price {
          line-height: 1.35rem;
          font-size: 1rem;
          letter-spacing: .04rem;
          color: #999;
        }

        .old {
          text-decoration: line-through;
        }

        .now {
          margin-left: .3rem;
          color: #fb0a32;
          .num {
            font-size: 1.31rem;
          }
        }

        .checked {
          width: 1.25rem;
          height: 1.25rem;
          line-height: 1.25rem;
          font-size: 1rem;
          background-color: #ff8611;
          color: #fff;
          border-radius: 0 .25rem;
        }
      }
    }

    .discount {
      .van-cell {
        padding: 0 .9375rem;
        color: #333;
        font-size: 1rem;
        line-height: 3.13rem;

        &::after {
          display: none;
        }

        &:first-child {
          &::after {
            display: block;
            left: 0;
          }
        }

        &:nth-child(2) {
          .van-cell__value {
            color: #ff8611;
          }
        }

        .van-icon-arrow:before {
          line-height: 3.13rem;
        }

        .van-cell__value {
          font-size: .94rem;
          color: #666;
        }
      }
    }

    .discount-popup {
      .popup-title {
        padding: 1.25rem 0 1rem .78rem;
        font-size: 1.13rem;
        line-height: 1.25rem;
        color: #222;
      }

      .card-list {
        padding: 1.25rem .94rem 4.5rem;
        height: 25.91rem;
      }

      .use-discount {
        bottom: 1.25rem;
        width: 13.06rem;
        line-height: 2.5rem;
        background-color: #ff4e00;
        border-radius: 1.25rem;
        font-size: 1rem;
        color: #fff;
      }
    }

    .notice {
      padding-bottom: 4.44rem;
      background-color: #f5f5f5;

      .inner {
        margin: 0 .75rem;
        padding: .63rem;
        font-size: .88rem;
        line-height: 1.38rem;
        color: #999;
      }
    }

    .pay-btn {
      padding-left: .78rem;
      border-top: .06rem #e8e8e8 solid;
      height: 3.13rem;
      line-height: 3.13rem;
      font-size: .88rem;
      color: #333;
      background-color: #fff;

      .num {
        font-size: 1.13rem;
        color: #fb0a32;
        margin-left: .63rem;
      }

      .btn {
        width: 10.63rem;
        background-color: #ff8611;
        color: #fff;
        font-size: 1.13rem;
      }
    }
  }

</style>
